const path = require('path')
const fs = require('fs')
const sharp = require('sharp')
const textToSVG = require('../utils/text-to-svg.js')

module.exports = async (ctx,next) => {
  const query = ctx.query
  const filepath = path.join('storage',path.sep, ctx.params.date, path.sep, ctx.params.file)
  const stat = fs.statSync(filepath)
  ctx.response.type = path.extname(ctx.params.file)
  if(Object.keys(query).length === 0) {
    ctx.set('Content-Length', stat.size)
    ctx.set('Last-Modified', stat.mtime.toUTCString())
    ctx.body = fs.createReadStream(filepath)
  } else {
    const width = parseInt(ctx.query.w) || null
    const height = parseInt(ctx.query.h) || null 

    const cacheFileName = generateCache(ctx.params.date, ctx.params.file , width, height)
    const originFileName =  path.join('storage',path.sep, ctx.params.date, path.sep, ctx.params.file)
    
    await fs.promises.mkdir(path.parse(cacheFileName).dir, { recursive: true })
    if (!fs.existsSync(cacheFileName)) {
      // 水印文字
      const watermarkBuffer = Buffer.from(textToSVG('WaterMark!')) 
      await sharp(originFileName)
        .resize(width, height)
        .composite([
          {
            // input: 'watermark-md.png', // 输入
            input: watermarkBuffer,
            gravity: 'southeast', // 位置，默认：center
            // tile: true // 重复
          }
        ])
        .sharpen()
        .toFile(cacheFileName)
    }
    ctx.body = fs.createReadStream(cacheFileName)
  }
}
function generateCache(date, file, width, height) {
  const cname = file.replace(/\./, '_' + (width || '') + '_' + (height || '') + '.')
  return path.join('cache',path.sep, date, path.sep, cname)
}
